#!/usr/bin/env python
#coding=utf-8
#Written by RAh-XePhON @ http://ToKyo-JuPiTer.Blogspot.com/
#0.1@2007-08-26
import os, sys, shutil
def cue_file_path():
	textt=""
	try:
		textt=sys.argv[1]
	except IndexError, message:
		print >> sys.stderr, 'Error!!!'
	#os.system( "zenity --info --text=" + textt )
	return textt
def name_file():
	textt=cue_file_path()
	print textt
	try:
		cue_file=open( textt )
	except IOError, message:
		print >> sys.stderr, 'File Not Found!'
		sys.exit(1)
	cue_body=cue_file.read()
	cue_file.close()
	cue_real=cue_body.splitlines()
	for i in cue_real:
		line=i.strip()
		words=line.split()
		if len(words) > 1:
			if words[0].upper() == "TRACK":	print "\n"+words[1], '   ',
			if words[0].upper() == "TITLE":	print " ".join(words[1:]), '   ',
			if words[0].upper() == "PERFORMER":	print " ".join(words[1:]),
	print '\n-----------------------------\n=============================\n-----------------------------'
	ind=0
	ogg_name=[["",""]]
	for i in cue_real:
		line=i.strip()
		words=line.split()
		if len(words) > 1:
			if words[0].upper() == "TRACK":
				#print "\n"+words[1], '   ',
				ind=words[1]
				ogg_name+=[[[""],[""]]]
				#print "|"+ind+"|"
			if words[0].upper() == "TITLE":
				#print " ".join(words[1:]), '   ',
				kname="_".join(words[1:])
				ogg_name[int(ind)][0]=kname.replace('"','',2)
			if words[0].upper() == "PERFORMER":
				#print " ".join(words[1:]),
				kname="_".join(words[1:])
				ogg_name[int(ind)][1]=kname.replace('"','',2)
	ogg_name[0][1]=ind
	return ogg_name
def re_name( ogg_name ):
	seep=".-."
	textt=cue_file_path()
	ind=ogg_name[0][1]
	wpd = os.path.dirname( textt )
	os.chdir( wpd )
	#print 'Working path:',
	#print os.listdir( os.curdir )
	for i in range(int(ind)+1):
		if i != 0:
			n="%02d." % i
			file_name_o = n+ogg_name[i][0]+seep+ogg_name[i][1]+seep+"".join(ogg_name[0][0])+".ogg"
			file_name = file_name_o.replace('/','\\')
			#wpd = os.path.dirname( textt )
			#os.chdir( wpd )
			#ogg_list = os.listdir( os.curdir )
			#print ogg_list
			if os.path.isfile( "%02d.ogg" % i ):
				print "shutil.move(", "%02d.ogg" % i, ",", file_name,  ")"
				shutil.move( "%02d.ogg" % i, file_name )
def main():
	print
	print os.path.abspath(__file__)
	print
	ogg_name = name_file()
	yon=raw_input('繼續？[y\\n]')
	if yon.lower() == 'y':	re_name( ogg_name )
if __name__ == "__main__":
	main()
	print '\n========\nNow Exit\n========\n'
	sys.exit(0)
